from datetime import datetime
import datetime
import time
import modbus_tk
import modbus_tk.defines as cst
import struct
import xlwt
from xlrd import open_workbook
from xlutils.copy import copy
from modbus_tk import modbus_tcp, hooks
import numpy
from socket import *
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
def Writexls(Name,Par_rows,X_dir,Y_dir):   #保存数据
    rexcel = open_workbook(Name)  # 用wlrd提供的方法读取一个excel文件
    excel = copy(rexcel)  # 用xlutils提供的copy方法将xlrd的对象转化为xlwt的对象
    table = excel.get_sheet(0)  # 用xlwt对象的方法获得要操作的sheet
    table.write(Par_rows, 0, Par_rows)
    table.write(Par_rows, 1, X_dir)  #X方向位置
    table.write(Par_rows, 2, Y_dir)  #Y方向位置
    excel.save(Name)
    """""""""""
def ushort_to_short(u_date):           #AGV当前位置，无符号转换为有符号数
    Value0 = struct.pack("H",u_date)
    return struct.unpack("h",Value0)
    """""""""""""""
AGV_IP = "192.168.1.94"
LOGGER = modbus_tk.utils.create_logger("console")  #modbus -TCP连接
MASTER = modbus_tcp.TcpMaster(host=AGV_IP , port=3001)
MASTER.set_timeout(5.0)
LOGGER.info("connected")
host = "localhost"
NavStatus = MASTER.execute(1, cst.READ_INPUT_REGISTERS, 1, 18, data_format="")
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S.%f')  # AGV状态正常，新建文件
XlsName = "Demo " + str(AGV_IP) + "_"+ str(now_time) + ".xls"
workBook = xlwt.Workbook()  # built xls
sht1 = workBook.add_sheet('采样数据')
sht1.write(0, 0, "NO.")
sht1.write(0, 1, "X方向位置")
sht1.write(0, 2, "Y方向位置")
workBook.save(XlsName)
time.sleep(3)
rows = 0
add00 = 0
while add00 < 10:
    NavStatus = MASTER.execute(1, cst.READ_INPUT_REGISTERS, 1, 18, data_format="")
    if NavStatus[13] == 1:
        str = input("请输入：");
        if str == "ok":
            add00 = add00 + 1
            NavStatus1 = MASTER.execute(1, cst.READ_INPUT_REGISTERS, 1, 18, data_format="")
            a = NavStatus[7]
            b = NavStatus[8]
            c = NavStatus[5]
            d = NavStatus[6]
            """""""""""""""""
            a1 = round(a[0] / 1000, 4) * 1000
            b1 = round(b[0] / 1000, 4) * 1000
            c1 = round(c[0] / 1000, 4) * 1000
            d1 = round(d[0] / 1000, 4) * 1000
            """""""""""
            X_dir = numpy.array([c, d], numpy.int16)
            X_dir.dtype = numpy.float32
            Y_dir = numpy.array([a, b], numpy.int16)
            Y_dir.dtype = numpy.float32
            X_dir = (", ".join(repr(e) for e in X_dir))
            Y_dir = (", ".join(repr(e) for e in Y_dir))
            print('X方向：{} ，Y方向：{}'.format(X_dir, Y_dir))
            rows = rows + 1
            Writexls(XlsName, rows, X_dir, Y_dir)
            time.sleep(5)
        else:
            print("输入错误！")
            time.sleep(0.5)
    continue
d = "{add00}组数据已收集完毕！"
print(d.format_map(vars()))

